<?php

namespace app\admin\middleware;

use app\common\model\mysql\RuleModel;
use think\facade\Cache;
use think\facade\Cookie;

class RuleMiddleware extends BaseMiddleware
{
    public function handle($request, \Closure $next)
    {
        $rules = Cache::get(Cookie::get('token'))['rules'];

        if (!in_array('*', $rules)) {
            $method = strtoupper($request->method());
            $route_path = $this->getPath($request);
            $data = explode('/', $route_path);
            $route_path = $data[0] . '/' . $data[1];

//            $rule_id = RuleModel::getAlone(['route' => $route_path, 'route_mode' => $method], 'id');
            $rule_id = RuleModel::getAlone(['route' => $route_path], 'id');

            if (empty($rule_id) || !in_array($rule_id, $rules)) {
                if (!$request->isAjax() && $request->isGet()) {
                    return redirect('/admin/error?code=403&msg=您没有权限进行操作&desc=路由：' . $request->url());
                }
                return json(['msg' => '您没有权限进行操作，请联系管理员', 'status' => '-2']);
            }
        }
        return $next($request);
    }

    protected function getPath($request)
    {

        $route_info = $request->rule()->getRule();

        $route_rule = str_replace('<id>', ':id', $route_info);

        return 'admin' . '/' . $route_rule;
    }
}
